package com.jz.community.moduleauthorization.login.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.bean.LoginInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.GetUserInfoTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CommSystemUtil;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.TimeUtils;
import com.jz.community.basecomm.utils.WXUtils;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.commview.view.widget.LoginButton;
import com.jz.community.moduleauthorization.R;
import com.jz.community.moduleauthorization.R2;
import com.jz.community.moduleauthorization.login.bean.LoginType;
import com.jz.community.moduleauthorization.login.presenter.LoginPresenter;
import com.jz.community.moduleauthorization.login.task.GetLoginCodeTask;
import com.jz.community.moduleauthorization.login.task.GetLoginWeChatTask;
import com.jz.community.moduleauthorization.utils.LoginEmptyUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.handler.UMWXHandler;
import com.umeng.socialize.utils.SocializeUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by Tony.Fan on 2018/3/19 16:01
 * <p>
 * 登录
 */
@Route(path = RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN)
public class LoginActivity extends BaseMvpActivity<LoginView.View, LoginPresenter> implements LoginView.View {
    @BindView(R2.id.login_phone_code_et)
    EditText loginPhoneCodeEt;
    @BindView(R2.id.login_obtain_code_bt)
    Button loginObtainCodeBt;
    @BindView(R2.id.login_code_et)
    EditText loginCodeEt;
    @BindView(R2.id.login_code_layout)
    LinearLayout loginCodeLayout;
    @BindView(R2.id.login_phone_et)
    EditText loginPhoneEt;
    @BindView(R2.id.login_pwd_et)
    EditText loginPwdEt;
    @BindView(R2.id.login_pwd_layout)
    LinearLayout loginPwdLayout;
    @BindView(R2.id.login_pwd_title_tv)
    TextView loginPwdTitleTv;
    @BindView(R2.id.login_code_title_tv)
    TextView loginCodeTitleTv;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.login_btn)
    LoginButton loginButton;
    @BindView(R2.id.rl_content)
    LinearLayout rl_content;
    @BindView(R2.id.title_name)
    TextView title_name;

    private TimeUtils timeUtils;
    private String registrationID;
    private boolean isLoginMode = false; //登录方式

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstants.WEIXIN_LOGIN_INTENT_ACTION);
        registerReceiver(weChatCodeReceiver, intentFilter);
        setImmersionBar(titleToolbar);
        loginSelectedTextColor(R.color.font_black, R.color.font_gary, true);
        titleRight.setTextColor(ContextCompat.getColor(this, R.color.login_red));
        title_name.setTextColor(ContextCompat.getColor(this, R.color.font_black));
        title_name.getPaint().setTypeface(Typeface.DEFAULT_BOLD);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_login_layout;
    }

    @Override
    protected void initDatas() {
        registrationID = JPushInterface.getRegistrationID(this);
        registerWeChatApp();
        initTitle("登录", "注册");
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleRight.setOnClickListener(v -> {
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_REGISTER);
            finish();
        });
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginBtnClick(v);
            }
        });
    }

    @OnClick(R2.id.login_pwd_title_tv)
    void loginPwdLayout() {
        SHelper.gone(loginCodeLayout);
        SHelper.vis(loginPwdLayout);
        loginSelectedTextColor(R.color.font_black, R.color.font_gary, true);
        isLoginMode = false;
    }

    @OnClick(R2.id.login_code_title_tv)
    void loginCodeLayout() {
        SHelper.vis(loginCodeLayout);
        SHelper.gone(loginPwdLayout);
        loginSelectedTextColor(R.color.font_gary, R.color.font_black, false);
        isLoginMode = true;
    }

    //登录
    public void loginBtnClick(View view) {
        CommUtils.hideKeyboard(view, this);
        handleLoginShowUI();
    }

    //忘记密码
    public void loginForgetPwdClick(View view) {
        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_RESET_PWD);
    }

    //微信登录
    public void loginBtnWechatClick(View view) {
        if (WXUtils.getInstance().isWxInstalledAndSurported(this)) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = AppConstants.WX_LOGIN_SCOPE;
            req.state = AppConstants.ACTION_LOGIN;
            api.sendReq(req);
        }
    }


    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(LoginActivity.this, "成功了", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(LoginActivity.this, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };

    /**
     * 不通登录方式选中样式
     *
     * @param loginPwdTvColor
     * @param loginCodeTvColor
     */
    private void loginSelectedTextColor(int loginPwdTvColor, int loginCodeTvColor, boolean isTextPaint) {
        loginPwdTitleTv.setTextColor(ContextCompat.getColor(this, loginPwdTvColor));
        loginCodeTitleTv.setTextColor(ContextCompat.getColor(this, loginCodeTvColor));
        if (isTextPaint) {
            loginPwdTitleTv.getPaint().setTypeface(Typeface.DEFAULT_BOLD);
            loginCodeTitleTv.getPaint().setTypeface(Typeface.DEFAULT);
            loginPwdTitleTv.setTextSize(16);
            loginCodeTitleTv.setTextSize(14);
        } else {
            loginPwdTitleTv.getPaint().setTypeface(Typeface.DEFAULT);
            loginCodeTitleTv.getPaint().setTypeface(Typeface.DEFAULT_BOLD);
            loginPwdTitleTv.setTextSize(14);
            loginCodeTitleTv.setTextSize(16);
        }
        loginPwdTitleTv.invalidate();
        loginCodeTitleTv.invalidate();
    }

    //处理登录UI
    private void handleLoginShowUI() {

        if (isShowLoginPhoneUI() && !isLoginMode) {
            handleLoginPhone(registrationID);
        }

        if (isShowLoginPhoneUI() && isLoginMode) {
            handleLoginCode();
        }
    }

    /**
     * 手机密码登录
     *
     * @param registrationID
     */
    private void handleLoginPhone(String registrationID) {
        String loginName = loginPhoneEt.getText().toString().trim();
        String loginPwd = loginPwdEt.getText().toString().trim();
        mPresenter.getLoginInfo(loginName, loginPwd, LoginType.DEFUALT.getTag(), "", CommUtils.getDeviceID(this), registrationID);
    }

    /**
     * 手机验证码登录
     */
    private void handleLoginCode() {
        String loginCodeName = loginPhoneCodeEt.getText().toString().trim();
        String loginCodePwd = loginCodeEt.getText().toString().trim();
        new GetLoginCodeTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                LoginInfo loginInfo = (LoginInfo) o;
                if (!Preconditions.isNullOrEmpty(loginInfo)) {
                    loginStateCallBack(loginInfo, true);
                }
            }
        }).execute(loginCodeName, loginCodePwd);
    }


    /**
     * 登录状态回调处理
     *
     * @param loginInfo
     */
    private void loginStateCallBack(LoginInfo loginInfo, boolean isLoginWay) {

        if (Preconditions.isNullOrEmpty(loginInfo)) {
            return;
        }

        if (!Preconditions.isNullOrEmpty(loginInfo.getAccess_token())) {
            saveUserMsg(loginInfo);
            getUserInfo();
            sendToLoginState(true, isLoginWay);
        } else {
            WpToast.l(LoginActivity.this, loginInfo.getMessage());
            refreshRegainBackground();
        }
    }

    /**
     * 刷新按钮
     */
    private void refreshRegainBackground() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loginButton.regainBackground("登录");
            }
        }, 1000);
    }

    /**
     * 保存用户基本信息
     *
     * @param loginInfo
     */
    private void saveUserMsg(LoginInfo loginInfo) {
        BaseSpUtils.getInstance().setAccessToken(LoginActivity.this, loginInfo.getAccess_token());
        BaseSpUtils.getInstance().setRefreshToken(LoginActivity.this, loginInfo.getRefresh_token());
        BaseSpUtils.getInstance().setOpenid(LoginActivity.this, loginInfo.getOpenid());
        BaseSpUtils.getInstance().setWeChatToken(LoginActivity.this, loginInfo.getWxToken());
        if (!Preconditions.isNullOrEmpty(loginInfo.getProfile())) {
            BaseSpUtils.getInstance().setUserId(LoginActivity.this, loginInfo.getProfile().getAttributes().getUser_id());
        }
    }

    /**
     * 微信登录
     *
     * @param code
     */
    private void handleLoginWechat(String code) {
        new GetLoginWeChatTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                LoginInfo loginInfo = (LoginInfo) o;
                loginStateCallBack(loginInfo, false);
                BaseSpUtils.getInstance().setWxUd(LoginActivity.this, loginInfo.getUnionid());
            }
        }).execute(code);
    }

    //第三方微信登录通知广播
    BroadcastReceiver weChatCodeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            handleLoginWechat(code);
        }
    };

    /**
     * 是否默认用户名、密码登录
     *
     * @return
     */
    private boolean isShowLoginPhoneUI() {
        if (isLoginMode) {
            return isJudgeLogin(false, loginPhoneCodeEt.getText().toString().trim(), loginCodeEt.getText().toString().trim());
        } else {
            return isJudgeLogin(true, loginPhoneEt.getText().toString().trim(), loginPwdEt.getText().toString().trim());
        }
    }

    //获取验证码
    public void loginObtainCodeBtnClick(View view) {
        String loginPhone = loginPhoneCodeEt.getText().toString().trim();
        if (LoginEmptyUtils.isLoginPhone(this, loginPhone)) {
            mPresenter.getLoginSmsCode("1", loginPhone);
        }
    }

    /**
     * 判断选择登录状态
     *
     * @param isLoginState
     * @param loginName
     * @param loginPwd
     * @return
     */
    private boolean isJudgeLogin(boolean isLoginState, String loginName, String loginPwd) {
        if (isLoginState) {
            return LoginEmptyUtils.isEmptyPasLogin(this, loginName, loginPwd);
        } else {
            return LoginEmptyUtils.isEmptyCodeLogin(this, loginName, loginPwd);
        }
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    public void showLoginInfo(LoginInfo loginInfo) {
        if (!Preconditions.isNullOrEmpty(loginInfo)) {
            loginStateCallBack(loginInfo, true);
        }
    }

    //发送登录状态
    private void sendToLoginState(boolean isLogin, boolean isLoginWay) {
        ToLoginEvent toLoginEvent = new ToLoginEvent();
        if (isLoginWay) {
            toLoginEvent.setToPwdLogin(isLogin);
            saveLoginState(1);
        } else {
            toLoginEvent.setToWeChatLogin(isLogin);
            saveLoginState(2);
        }
        RxBus.getInstance().post(toLoginEvent);
        WpToast.l(this, "登录成功");
        bindJupshID();
        finish();
    }

    /**
     * 用户信息
     */
    private void getUserInfo() {
        new GetUserInfoTask(this, o -> {
        }).execute();
    }

    /**
     * 绑定推送ID
     */
    private void bindJupshID() {
        mPresenter.getBindJupsh(getParam(JPushInterface.getRegistrationID(this)));
    }

    /**
     * 绑定推送参数
     *
     * @param jpushid
     * @return
     */
    private HashMap<String, Object> getParam(String jpushid) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userid", BaseSpUtils.getInstance().getUserId(this));
        hashMap.put("usertype", "member");
        hashMap.put("jpushid", jpushid);
        hashMap.put("osversion", CommSystemUtil.getSystemVersion());
        hashMap.put("ostype", 1);
        hashMap.put("manufacturers", CommSystemUtil.getDeviceBrand());
        return hashMap;
    }

    /**
     * 保存登录状态
     *
     * @param loginType
     */
    private void saveLoginState(int loginType) {
        BaseSpUtils.getInstance().setLoginType(this, loginType);
        BaseSpUtils.getInstance().setIsLogin(this, true);
    }

    @Override
    public void showSmsCodeInfo(LoginInfo baseResponseInfo) {
        handelSmsCodeState(baseResponseInfo);
    }

    @Override
    public void showResetPwdInfo(BaseResponseInfo userInfo) {

    }

    @Override
    public void showError() {
        refreshRegainBackground();
    }

    /**
     * 验证码结果处理状态
     *
     * @param baseResponseInfo
     */
    private void handelSmsCodeState(BaseResponseInfo baseResponseInfo) {
        if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
            if (timeUtils == null) {
                WpToast.l(this, "验证码发送成功");
                timeUtils = new TimeUtils(120 * 1000, 1000, LoginActivity.this, loginObtainCodeBt);
            }
            timeUtils.start();
        } else {
            WpToast.l(this, baseResponseInfo.getMessage());
        }
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeUtils != null) {
            timeUtils.cancel();
        }
        if (weChatCodeReceiver != null) {
            unregisterReceiver(weChatCodeReceiver);
        }
    }
}
